<?php
namespace Modules\Stats\Entities;

use Modules\Core\Entities\BaseEntity as Model;

use Modules\User\Entities\User;

use ThrowException;

// 用户类
class UserStats extends Model
{
    protected $guarded = [];
    protected $table = 'stats_user';
    protected $appends = [];

    protected $casts = [
    ];

    static public $resourceName = '用户统计';

    public function user()
    {
    	return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    public function scopeSearch($query, $key)
    {
        if (!$key) {
            return $query;
        }
        
        // 搜索手机号
        $user = User::where('phone', $key)->first();

        if (!$user) {
            return $query->where('id', '<', 0);
        }

        return $query->where('user_id', $user->id);
    }
    
    static public function beforeGetList($options)
    {
        if (@$options['sort_by']) {
            $arr = explode('-', $options['sort_by']);

            $options['order_by'] = [
                $arr[0] => $arr[1]
            ];
        }

        return $options;
    }

    // 更新总支付和总获得
    public function updateAllStats()
    {
        $item = $this;
        $item->update([
                'all_pay_money_price' => $item->box_pay_money_price + $item->yfs_pay_money_price + $item->fudai_pay_money_price,
                'all_pay_score_price' => $item->box_pay_score_price + $item->yfs_pay_score_price + $item->fudai_pay_score_price,
                'all_get_money_price' => $item->box_get_money_price + $item->yfs_get_money_price + $item->fudai_get_money_price,
                'all_get_score_price' => $item->box_get_score_price + $item->yfs_get_score_price + $item->fudai_get_score_price,
            ]);
    }
}
